var winston = require('winston');
var mysql = require('mysql');

module.exports = function(pool, req, res, next){
	var uriMap = req.params.uriMap;
	var referer = req.protocol + "://" + req.hostname + req.originalUrl;
	var ou = referer.split('?')[0];
	var ip = req.ip;
	// test if user access the page from wechat
	var ua = String.from(req.header('user-agent'));
	var userAgent = ua.match(/micromessenger/i) ? 'wechat' : 'other';
	winston.info(ua, userAgent);
	var bg = req.query.bg || 'ffffff';
	
	var queryString = 'SELECT share_content FROM share_list where uri_map="' + uriMap + '"';
	pool.getConnection(function(err, connection){
		if(err){
			winston.error('DB connection error: ' + err);
			res.status(500).send('DB connection error: ' + err);
		}
		connection.query(queryString, function(err, rows){
			if(err){
				winston.error('DB query error: ' + err);
				res.status(500).send('DB query error: ' + err);
			}else{
				if(rows.length > 0){
					var shareContent = rows[0].share_content;
					queryString = 'SELECT event_id, filename, is_portrait FROM photo_list where photo_id RLIKE "' + shareContent + '"';
					connection.query(queryString, function(err, rows){
						if(err){
							winston.error('DB query error: ' + err);
							res.status(500).send('DB query error: ' + err);
						}else{
							rows.forEach(function(row){
								var url = req.protocol + "://" + req.hostname + "/assets/" + row.event_id + "/" + row.filename;
								row.url = url;
							});
							rows.qrCode = req.protocol + "://" + req.hostname + "/qr/" + encodeURIComponent(ou);
							rows.uri = ou;
							res.render('share/' + rows[0]['event_id'], {data: rows, bg: bg});

							// record access of share page to db
							queryString = 'INSERT INTO share_access (referer, event_id, ip, uri_map, user_agent, timestamp) VALUES (?, ?, ?, ?, ?, ?)';
							var params = [encodeURIComponent(referer), rows[0]['event_id'], String.from(ip), uriMap, userAgent, String.from(Date.now())];
							connection.query(mysql.format(queryString, params), function(err){
								if(err){
									winston.error('DB query error: ' + err);
								}
							});
						}
					});
					
				}else{
					res.end('Search 0 photo from the ' + uriMap);
				}
			}
			connection.release();
		});
	});
	
	
}